package format

import (
	"encoding/json"
	"fmt"
	"geekai/api/dto/response"
	"geekai/core/store"
	"geekai/core/types"
	"github.com/go-redis/redis/v8"
)

type TouTiaoFormatService struct {
	Url       string
	RedisHash *store.RedisHash
}

func NewTouTiaoFormatService(redisCli *redis.Client) *TouTiaoFormatService {
	return &TouTiaoFormatService{
		Url:       types.TOU_TIAO,
		RedisHash: store.NewRedisHash(types.HOT_SEARCH_KEY, redisCli),
	}
}

func (s *TouTiaoFormatService) Format(body []byte) {
	resp := response.ToutiaoResponse{}
	if err := json.Unmarshal(body, &resp); err != nil {
		log.Errorf("解析 JSON 失败：%v\n", err)
	}
	var formattedSlice []response.TouTiaoFormattedTopic
	for _, topic := range resp.Data {
		formattedTopic := response.TouTiaoFormattedTopic{
			ID:    topic.ClusterIdStr,
			Title: topic.Title,
			URL:   fmt.Sprintf(types.TOU_TIAO_VISIT_URL, topic.ClusterIdStr),
		}
		if topic.LabelUri.URL != "" {
			formattedTopic.Extra.Icon = topic.LabelUri.URL
		}
		formattedSlice = append(formattedSlice, formattedTopic)
	}
	formattedSlice = formattedSlice[:5]
	encodeData, err := json.Marshal(formattedSlice)
	if err != nil {
		log.Errorf("json编码出现错误：%v\n", err)
		return
	}
	touTiaoCacheMap := map[string]string{
		types.TOU_TIAO_HOT_SEARCH_FIELD: string(encodeData),
	}
	s.RedisHash.HSet(touTiaoCacheMap)
}
